package com.springboot.util;

import cn.hutool.db.Db;
import cn.hutool.db.handler.BeanHandler;
import cn.hutool.db.handler.BeanListHandler;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;

import java.sql.SQLException;
import java.util.List;

@Slf4j
public class WinDbUtil {

    /**
     * 执行sql
     * @param sql
     * @param params
     * @return
     */
    public static int executeUpdateSql(String sql, Object... params) {
        try {
            log.info("WinDbUtil.executeUpdateSql：sql：{}, params：{}", sql, JSON.toJSONString(params));
            Db.use().execute(sql, params);
        } catch (SQLException ex) {
            log.info("执行错误!!");
            ex.printStackTrace();
        }
        return 0;
    }

    /**
     * 查询sql
     * @param sql
     * @param params
     * @return
     */
    public static <T> T queryForOneRow(String sql, Class<T> clazz, Object... params) {
        return queryForOneRow(null, sql, clazz, params);
    }

    /**
     * 查询sql
     * @param db null -> IA, o32_db -> o32
     * @param sql
     * @param params
     * @return
     */
    public static <T> T queryForOneRow(String db, String sql, Class<T> clazz, Object... params) {
        T queryResult = null;
        try {
            log.info("WinDbUtil.queryForOneRow：db: {}, sql：{}, params：{}", db, sql, JSON.toJSONString(params));
            queryResult = Db.use(db).query(sql, new BeanHandler<>(clazz), params);
        } catch (SQLException ex) {
            log.error("执行错误!!" + ex);
            ex.printStackTrace();
        }
        return queryResult;
    }

    /**
     * 查询sql
     * @param sql
     * @param params
     * @return
     */
    public static <T> List<T> queryList(String sql, Class<T> clazz, Object... params) {
        return queryList(null, sql, clazz, params);
    }

    /**
     * 查询sql
     * @param db null -> IA, o32_db -> o32
     * @param sql
     * @param params
     * @return
     */
    public static <T> List<T> queryList(String db, String sql, Class<T> clazz, Object... params) {
        List<T> queryResult = null;
        try {
            log.info("WinDbUtil.queryList：db: {}, sql：{}, params：{}", db, sql, JSON.toJSONString(params));
            queryResult = Db.use(db).query(sql, new BeanListHandler<>(clazz), params);
        } catch (SQLException ex) {
            log.error("执行错误!!" + ex);
            ex.printStackTrace();
        }
        return queryResult;
    }


}
